﻿using System;
using System.Collections.Generic;
using System.Transactions;
using MRGSP.SurveyMaster.Core.Model;
using MRGSP.SurveyMaster.Core.Repository;


namespace MRGSP.SurveyMaster.Data
{
    public class SurveySessionRepository : BaseRepository, ISurveySessionRepository
    {
        public SurveySessionRepository(IConnectionFactory connFactory)
            : base(connFactory)
        {
        }

        public IEnumerable<SurveySession> GetPageForUser(int page, int pageSize, long userId)
        {
            return DbUtil.ExecuteReaderSp<SurveySession>("getSurveysForUser", Cs, new { pageSize, page, userId });
        }

        public int CountForUser(long userId)
        {
            return (int)DbUtil.ExecuteScalarSp("getSurveysForUserCount", Cs, new { userId });
        }

        public int Done(long id)
        {
            return DbUtil.ExecuteNonQuerySp("doneSurveySession", Cs, new { id });
        }

        public long Insert(long surveyId, long userId, IEnumerable<Answer> answers)
        {
            using(var scope = new TransactionScope())
            {
                var sessionId = Convert.ToInt64(DbUtil.ExecuteScalarSp("insertSurveySession", Cs, new { surveyId, userId }));

                foreach (var answer in answers)
                    DbUtil.ExecuteNonQuerySp("insertAnswer", Cs, new { sessionId, answer.QuestionId, answer.Value });

                scope.Complete();
                return sessionId;
            }
        }

        public long Update(long sessionId, IEnumerable<Answer> answers)
        {
            using (var scope = new TransactionScope())
            {
                DbUtil.ExecuteNonQuerySp("deleteAnswersBySessionId", Cs, new { sessionId });

                foreach (var answer in answers)
                    DbUtil.ExecuteNonQuerySp("insertAnswer", Cs, new { sessionId, answer.QuestionId, answer.Value });

                scope.Complete();
                return sessionId;
            }
        }

        public SurveySession Get(long id)
        {
            return DbUtil.Get<SurveySession>(id, Cs);
        }

        public IEnumerable<Answer> GetBySessionId(long sessionId)
        {
            return DbUtil.GetWhere<Answer>(new { sessionId }, Cs);
        }
    }
}